package revontuli.aMHD.datamanagement;

import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.ListIterator;

import revontuli.aMHD.aMHDApp;
import revontuli.aMHD.dataclasses.*;
import revontuli.aMHD.R;

import android.R.integer;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import android.text.format.Time;

public class DataManager {
	// databazova schema
	private static final String DATABASE_NAME = "trafficdata";
	private static final int DATABASE_VERSION = 1;
	
	private static final String STOP_TABLE = "stop";
	private static final String STOP_TABLE_CREATE = "create table " + STOP_TABLE + " ("
												+ "stop_id integer, "
												+ "stop_name text, "
												+ "latitude real, "
												+ "longitude real, "
												+ "zone integer, "
												+ "ondemand integer, "
												+ "active integer, "
												+ "stop_revision integer, "
												+ "favourite_boo integer default 0, "
												+ "primary key(stop_id));";

	private static final String STOPPLATFORMS_TABLE = "stopplatforms";
	private static final String STOPPLATFORMS_TABLE_CREATE = "create table " + STOPPLATFORMS_TABLE + " ("
															+ "stop_id integer, "
															+ "stop_platform integer, "
															+ "latitude real, "
															+ "longitude real, "
															+ "primary key(stop_id, stop_platform));";
	
	private static final String LINE_TABLE = "line";
	private static final String LINE_TABLE_CREATE = "create table " + LINE_TABLE + " ("
												+ "line_id integer, "
												+ "line_direction integer, "
												+ "line_name text, "
												+ "vehicle integer, "
												+ "active integer, "
												+ "exceptional_ind text, "
												+ "exceptional_desc text, "
												+ "line_revision integer, "
												+ "update_boo integer default 0, "
												+ "primary key(line_id, line_direction));";

	private static final String LINESTOPS_TABLE = "linestops";
	private static final String LINESTOPS_TABLE_CREATE = "create table " + LINESTOPS_TABLE + " ("
														+ "line_id integer, "
														+ "line_direction integer, "
														+ "stop_order integer, "
														+ "stop_id integer, "
														+ "platform_id integer, "
														+ "distance_time integer, "
														+ "primary key(line_id, line_direction, stop_id));";
	
	private static final String LINESTOPDEPART_TABLE = "linestopdepart";
	private static final String LINESTOPDEPART_TABLE_CREATE = "create table " + LINESTOPDEPART_TABLE + " ("
															+ "line_id integer, "
															+ "line_direction integer, "
															+ "stop_id integer, "
															+ "departure_time text, "
															+ "schedule_type integer, "
															+ "exceptional_route_id integer, "
															+ "line_revision integer, "
															+ "primary key(line_id, line_direction, stop_id, departure_time, schedule_type));";
	
	private Context mContext;
	private DatabaseHelper mDBHelper;
	private SQLiteDatabase db;
	
	public DataManager(Context c) {
		this.mContext = c;
		mDBHelper = new DatabaseHelper(mContext);
	}
	
	private static class DatabaseHelper extends SQLiteOpenHelper {
		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Log.i(aMHDApp.TAG, STOP_TABLE_CREATE);
			db.execSQL(STOP_TABLE_CREATE);
			Log.i(aMHDApp.TAG, STOPPLATFORMS_TABLE_CREATE);
			db.execSQL(STOPPLATFORMS_TABLE_CREATE);
			Log.i(aMHDApp.TAG, LINE_TABLE_CREATE);
			db.execSQL(LINE_TABLE_CREATE);
			Log.i(aMHDApp.TAG, LINESTOPS_TABLE_CREATE);
			db.execSQL(LINESTOPS_TABLE_CREATE);
			Log.i(aMHDApp.TAG, LINESTOPDEPART_TABLE_CREATE);
			db.execSQL(LINESTOPDEPART_TABLE_CREATE);
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(aMHDApp.TAG, "Upgrading database from " + oldVersion + " to " + newVersion);
			db.execSQL("DROP TABLE IF EXISTS " + STOP_TABLE);
			db.execSQL("DROP TABLE IF EXISTS " + STOPPLATFORMS_TABLE);
			db.execSQL("DROP TABLE IF EXISTS " + LINE_TABLE);
			db.execSQL("DROP TABLE IF EXISTS " + LINESTOPS_TABLE);
			db.execSQL("DROP TABLE IF EXISTS " + LINESTOPDEPART_TABLE);
			onCreate(db);
		}
	}
	
	public DataManager open() throws SQLException {
		db = mDBHelper.getWritableDatabase();
		return this;
	}
	
	public void close() {
		mDBHelper.close();
		Log.i(aMHDApp.TAG, "Database closed.");
	}
	
	// metody na aktualizaciu dat v databaze
	
	/**
	 * metoda na spustenie stahovania na pozadi, len vytvori asynctask a spusti ho
	 */
	public void updateAllData() {
		//spustime aktualizaciu na pozadi
		Log.i(aMHDApp.TAG, "Updating in background");
		UpdateTask task = new UpdateTask();
		task.execute();
	}
	
	/**
	 * metoda, ktoru vola asynctask a sluzi len na nainsertovanie zastavok stiahnutych zo servera do databazy
	 * @param zoznam
	 */
	private void insertStopsIntoDB(ArrayList<Stop> zoznam) {
		this.open();
		ListIterator<Stop> it = zoznam.listIterator();
		while (it.hasNext()) {
			Stop zastavka = it.next();
			
			ContentValues values = new ContentValues();
			values.put("stop_id", zastavka.id);
			values.put("stop_name", zastavka.name);
			values.put("latitude", zastavka.location.getLatitude());
			values.put("longitude", zastavka.location.getLongitude());
			values.put("zone", zastavka.zone);
			values.put("ondemand", zastavka.ondemand);
			values.put("active", zastavka.active);
			values.put("stop_revision", zastavka.stop_revision);
			db.insert(STOP_TABLE, null, values);
		}
	}
	
	private void deleteStopsFromDB(ArrayList<Stop> zoznam) {
		this.open();
		ListIterator<Stop> it = zoznam.listIterator();
		while (it.hasNext()) {
			Stop zastavka = it.next();
			db.delete(STOP_TABLE, "stop_id=?", new String[] {Integer.toString(zastavka.id)});
			db.delete(STOPPLATFORMS_TABLE, "stop_id=?", new String[] {Integer.toString(zastavka.id)});
		}
	}
	
	private void insertLinesIntoDB(ArrayList<Line> zoznam) {
		this.open();
		ListIterator<Line> it = zoznam.listIterator();
		while (it.hasNext()) {
			Line linka = it.next();
			
			ContentValues values = new ContentValues();
			values.put("line_id", linka.id);
			values.put("line_direction", linka.direction);
			values.put("line_name", linka.name);
			values.put("vehicle", linka.vehicle);
			values.put("active", linka.active);
			values.put("exceptional_ind", linka.exceptional_ind);
			values.put("exceptional_desc", linka.exceptional_desc);
			values.put("line_revision", linka.line_revision);
			db.insert(LINE_TABLE, null, values);

			if (linka.stops != null && linka.stops.size() > 0) {
				ListIterator<Line.LineStop> it2 = linka.stops.listIterator();
				while (it2.hasNext()) {
					Line.LineStop zastavka = it2.next();
					
					values = new ContentValues();
					values.put("line_id", linka.id);
					values.put("line_direction", linka.direction);
					values.put("stop_order", zastavka.order);
					values.put("stop_id", zastavka.id);
					values.put("platform_id", zastavka.platform);
					values.put("distance_time", zastavka.distance_time);
					db.insert(LINESTOPS_TABLE, null, values);
				}
			}
		}
	
	}
	
	private void deleteLinesFromDB(ArrayList<Line> zoznam) {
		this.open();
		ListIterator<Line> it = zoznam.listIterator();
		while (it.hasNext()) {
			Line linka = it.next();
			db.delete(LINE_TABLE, "line_id=?", new String[] {Integer.toString(linka.id)});
			db.delete(LINESTOPS_TABLE, "line_id=?", new String[] {Integer.toString(linka.id)});
			//db.delete(LINESTOPDEPART_TABLE, "line_id=?", new String[] {Integer.toString(linka.id)});
		}
	}
	
	public void insertDeparturesIntoDB(ArrayList<Departure> odchody) {
		this.open();
		ListIterator<Departure> it = odchody.listIterator();
		while (it.hasNext()) {
			Departure odchod = it.next();
			
			ContentValues values = new ContentValues();
			values.put("line_id", odchod.lineID);
			values.put("line_direction", odchod.lineDirection);
			values.put("stop_id", odchod.stopID);
			values.put("departure_time", odchod.departureTime.format2445());
			values.put("schedule_type", odchod.scheduleType);
			values.put("exceptional_route_id", odchod.exceptionalRouteID);
			values.put("line_revision", (odchod.lineRevision==0)?null:odchod.lineRevision);
			db.insert(LINESTOPDEPART_TABLE, null, values);
		}
	}

	public void deleteDeparturesFromDB(ArrayList<Departure> odchody) {
		this.open();
		ListIterator<Departure> it = odchody.listIterator();
		while (it.hasNext()) {
			int linka = it.next().lineID;
			db.delete(LINESTOPDEPART_TABLE, "line_id=?", new String[] {Integer.toString(linka)});
		}
	}
	
	// metody na ziskanie dat z databazy
	
	/**
	 * Overenie, ci je linka ulozena v databaze
	 */
	public boolean isLineStored(int line_id) {
		this.open();
		Cursor mCursor = db.query(true, LINE_TABLE, new String[] {"update_boo"}, "line_id = ?", new String[] {Integer.toString(line_id)}, null, null, null, null);
		if ((mCursor != null) && (mCursor.getCount() == 1)) {
			mCursor.moveToFirst();
			int cislo = mCursor.getInt(0);
			return (cislo==1)?true:false;
		}
		Log.e(aMHDApp.TAG, "isLineStored returns more rows");
		return false;
	}
	
	/**
	 * Vrati zoznam okolitych zastavok
	 * @param mLocation
	 * @param mRange
	 * @return
	 */
	public ArrayList<Stop> getNearbyStops(Location mLocation, int mRange) {
		this.open();
		ArrayList<Stop> zoznam = new ArrayList<Stop>();
		Cursor mCursor = db.query(false, STOP_TABLE, new String[] {"stop_id", "stop_name", "latitude", "longitude",
				"zone", "ondemand", "active", "stop_revision", "favourite_boo"}, "active = 1", null, null, null, null, null);
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
//			Toast.makeText(mContext, "not null", Toast.LENGTH_SHORT).show();
			mCursor.moveToFirst();
			do {
				Location loc = new Location((String) null);
				loc.setLatitude(mCursor.getDouble(2));
				loc.setLongitude(mCursor.getDouble(3));
				int dist = (int) mLocation.distanceTo(loc);
				
				if (dist <= (mRange + aMHDApp.ADDITIONAL_SEARCH_RANGE)) {
					Stop zastavka = new Stop(mCursor.getInt(0));
					zastavka.name = mCursor.getString(1);
					zastavka.location = loc;
					zastavka.zone = mCursor.getInt(4);
					if (mCursor.getInt(5) == 1) {
						zastavka.ondemand = true;
					} else {
						zastavka.ondemand = false;
					}
					if (mCursor.getInt(6) == 1) {
						zastavka.active = true;
					} else {
						zastavka.active = false;
					}
					zastavka.stop_revision = mCursor.getInt(7);
					if (mCursor.getInt(8) == 1) {
						zastavka.favourite = true;
					} else {
						zastavka.favourite = false;
					}
					zastavka.distance = dist;
					zoznam.add(zastavka);
				}
				Collections.sort(zoznam, new StopDistanceComparator());
			} while (mCursor.moveToNext());
		} else {
			//ziadne zaznamy o zastavkach v db
			return null;
		}
		return zoznam;
	}
	
	/**
	 * Zoznam vsetkych liniek, ktore odchadzaju zo zastavky. Trasy zastavok su ulozene v databaze, preto nepotrebujeme pripojenie.
	 * @param stop_id
	 * @return
	 */
	public ArrayList<String> getLinesFromStop(int stop_id) {
		this.open();
		ArrayList<String> linky = new ArrayList<String>();
		Cursor mCursor = db.rawQuery(
				"select distinct l.line_name from "+LINE_TABLE+" l inner join "+LINESTOPS_TABLE+" ls "+
				"on l.line_id = ls.line_id where l.active = 1 and ls.stop_id="+Integer.toString(stop_id),null);
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
			mCursor.moveToFirst();
			do {
				linky.add(mCursor.getString(0));
			} while (mCursor.moveToNext());
		}
		
		Collections.sort(linky);
		return linky;
		
	}
	
	public String getLineName(int line_id) {
		this.open();
		Cursor mCursor = db.rawQuery(
				"select distinct line_name from "+LINE_TABLE+" "+
				"where line_id=?",new String[] {Integer.toString(line_id)});
		if ((mCursor != null) && (mCursor.getCount() == 1)) {
			mCursor.moveToFirst();
			return mCursor.getString(0);
		}
		Log.e(aMHDApp.TAG, "getLineName returns more rows");
		return null;
	}
	
	public String getTerminusName(int line_id, int line_direction) {
		this.open();
		Cursor mCursor = db.rawQuery(
				"select stop_name "+
				"from "+STOP_TABLE+" "+
				"where stop_id = ( "+
				"select stop_id "+
				"from "+LINESTOPS_TABLE+" "+
				"where line_id = ? "+
				"and line_direction = ? "+
				"order by stop_order desc "+
				"limit 1);",
				new String[] {Integer.toString(line_id), Integer.toString(line_direction)});
		if ((mCursor != null) && (mCursor.getCount() == 1)) {
			mCursor.moveToFirst();
			return mCursor.getString(0);
		}
		Log.e(aMHDApp.TAG, "getTerminusName returns more rows");
		return null;
	}
	
	public int getLineVehicle(int line_id) {
		this.open();
		Cursor mCursor = db.rawQuery(
				"select distinct vehicle from "+LINE_TABLE+" "+
				"where line_id=?",new String[] {Integer.toString(line_id)});
		if ((mCursor != null) && (mCursor.getCount() == 1)) {
			mCursor.moveToFirst();
			return mCursor.getInt(0);
		}
		Log.e(aMHDApp.TAG, "getLineVehicle returns more rows");
		return 0;
	}
	
	public ArrayList<Integer> getLineIDsFromStop(int stop_id) {
		this.open();
		ArrayList<Integer> linky = new ArrayList<Integer>();
		Cursor mCursor = db.rawQuery(
				"select distinct line_id from "+LINESTOPS_TABLE+" "+
				"where stop_id=?",new String[] {Integer.toString(stop_id)});
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
			mCursor.moveToFirst();
			do {
				linky.add(Integer.parseInt(mCursor.getString(0)));
			} while (mCursor.moveToNext());
		}
		
		Collections.sort(linky);
		return linky;
		
	}
	
	/**
	 * Zoznam najblizsich odchodov zo zastavky
	 * @param stop_id
	 * @return
	 */
	public ArrayList<Departure> getStopSchedule(int stop_id) {
		ArrayList<Departure> mDeparts = new ArrayList<Departure>();
		ArrayList<Integer> mLines = getLineIDsFromStop(stop_id);
		this.open();
		ListIterator<Integer> it = mLines.listIterator();
		int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
		int scheduleType;
		if ((day == Calendar.SUNDAY) || (day == Calendar.SATURDAY)) {
			scheduleType = 2;
		} else {
			scheduleType = 1;
		}
		
		while (it.hasNext()) {
			int linka = it.next();
			if (!isLineStored(linka) && !aMHDApp.mDataManager.getOffline()) {
				
			} else {
				Cursor mCursor = db.query(LINESTOPDEPART_TABLE, new String[] {"line_direction", "departure_time", "exceptional_route_id"},
						"line_id = ? and stop_id=? and schedule_type = ? and substr(departure_time,10,6) > strftime('%H%M%S','now', 'localtime') and substr(departure_time,10,6) < strftime('%H%M%S','now','+2 hours','localtime')",
						new String[] {Integer.toString(linka), Integer.toString(stop_id), Integer.toString(scheduleType)}, null, null, null);
				if ((mCursor != null) && (mCursor.getCount() > 0)) {
					mCursor.moveToFirst();
					do {
						Departure depart = new Departure(linka, mCursor.getInt(0), stop_id);
						depart.departureTime.parse(mCursor.getString(1));
						depart.exceptionalRouteID = mCursor.getInt(2);
						depart.lineName = getLineName(linka);
						depart.terminusStopName = getTerminusName(linka, mCursor.getInt(0));
						depart.lineTypeID = getLineVehicle(linka);
						mDeparts.add(depart);
					} while (mCursor.moveToNext());
				}
			}
		}
		Collections.sort(mDeparts);
		return mDeparts;
	}
	
	/**
	 * Zoznam vsetkych zastavok
	 * @return
	 */
	public ArrayList<Stop> getAllStops() {
		ArrayList<Stop> mResult = new ArrayList<Stop>();
		this.open();
		Cursor mCursor = db.query(false, STOP_TABLE, new String[] {"stop_id", "stop_name", "favourite_boo"}, "active = 1", null, null, null, null, null);
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
			mCursor.moveToFirst();
			do {
				Stop mStop = new Stop(mCursor.getInt(0));
				mStop.name = mCursor.getString(1);
				mStop.favourite = (mCursor.getInt(2)==1)?true:false;
				
				mResult.add(mStop);
			} while (mCursor.moveToNext());
			Collections.sort(mResult, new StopAlphabetComparator());
		}
		return mResult;
	}
	
	/**
	 * Zoznam vsetkych liniek
	 * @return
	 */
	public ArrayList<Line> getAllLines(int vehicle) {
		ArrayList<Line> mResult = new ArrayList<Line>();
		this.open();
		Cursor mCursor = db.query(true, LINE_TABLE, new String[] {"line_id", "line_name", "update_boo"}, "active = 1 and exceptional_ind = '' and vehicle=?",
				new String[] {Integer.toString(vehicle)}, null, null, null, null);
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
			mCursor.moveToFirst();
			do {
				Line mLine = new Line(mCursor.getInt(0));
				mLine.name = mCursor.getString(1);
				mLine.update = (mCursor.getInt(2)==1)?true:false;
				mLine.vehicle = vehicle;
				
				mResult.add(mLine);
			} while (mCursor.moveToNext());
			Collections.sort(mResult);
		}
		return mResult;
	}
	
	public ArrayList<Integer> getAllFavLines() {
		ArrayList<Integer> mResult = new ArrayList<Integer>();
		this.open();
		Cursor mCursor = db.query(true, LINE_TABLE, new String[] {"line_id"}, "update_boo = 1", null, null, null, "line_id", null);
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
			mCursor.moveToFirst();
			do {
				mResult.add(mCursor.getInt(0));
			} while (mCursor.moveToNext());
		}
		
		return mResult;
	}
	
	public boolean setStopFavourite(int stop_id, int favourite) {
		this.open();
		ContentValues val = new ContentValues();
		val.put("favourite_boo", favourite);
		db.update(STOP_TABLE, val, "stop_id = ?", new String[] {Integer.toString(stop_id)});
		
		return false;
	}
	
	public boolean setLineFavourite(int line_id, int favourite) {
		this.open();
		ContentValues val = new ContentValues();
		val.put("update_boo", favourite);
		db.update(LINE_TABLE, val, "line_id = ?", new String[] {Integer.toString(line_id)});
		return false;
	}
	
	
	/**
	 * Vracia zoznam odchodov linky zo zastavky
	 * @param stop_id
	 * @param line_id
	 * @param day_type
	 * @param direction
	 * @return
	 */
	public ArrayList<DeparturesGrouped> getDepartures(int stop_id, int line_id, int day_type, int direction) {
		ArrayList<DeparturesGrouped> mResult = new ArrayList<DeparturesGrouped>();
		DeparturesGrouped odchody = new DeparturesGrouped();
		this.open();
		Log.e(aMHDApp.TAG, "dir "+Integer.toString(direction));
		Cursor mCursor = db.query(LINESTOPDEPART_TABLE, new String[] {"departure_time", "exceptional_route_id"}, "stop_id = ? and line_id = ? and schedule_type = ? and line_direction = ?", new String[] {Integer.toString(stop_id), Integer.toString(line_id), Integer.toString(day_type), Integer.toString(direction)}, null, null, "departure_time");
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
			mCursor.moveToFirst();
			do {
				Time cas = new Time();
				cas.parse(mCursor.getString(0));
				Log.e(aMHDApp.TAG, "cas "+cas.toString());
				if (odchody.hour < 0) {
					odchody.hour = cas.hour;
					odchody.minute.add(cas.minute);
				} else if (odchody.hour == cas.hour) {
					odchody.minute.add(cas.minute);
				} else if (odchody.hour != cas.hour) {
					mResult.add(odchody);
					odchody = new DeparturesGrouped();
					odchody.hour = cas.hour;
					odchody.minute.add(cas.minute);
				}
			} while (mCursor.moveToNext());
		}
		return mResult;
	}
	
	/**
	 * Vracia zoznam zastavok linky
	 * @param line_id
	 * @param direction
	 * @return
	 */
	public ArrayList<Stop> getRoute(int line_id, int direction) {
		ArrayList<Stop> mResult = new ArrayList<Stop>();
		Stop zastavka;
		this.open();
		Cursor mCursor = db.rawQuery("select s.stop_id, s.stop_name, ls.distance_time from "+STOP_TABLE+" s, "+LINESTOPS_TABLE+" ls "
				+"where ls.stop_id = s.stop_id and ls.line_id = ? and ls.line_direction = ? order by ls.stop_order",new String[] {Integer.toString(line_id), Integer.toString(direction)});
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
			mCursor.moveToFirst();
			do {
				zastavka = new Stop(mCursor.getInt(0));
				zastavka.name = mCursor.getString(1);
				zastavka.distance = mCursor.getInt(2);
				mResult.add(zastavka);
			} while (mCursor.moveToNext());
		}
		
		return mResult;
	}
	
	public int getStopOrder(int line_id, int direction, int stop_id) {
		this.open();
		Cursor mCursor = db.query(LINESTOPS_TABLE, new String[] {"stop_order"}, "line_id = ? and line_direction = ? and stop_id = ?", new String[] {Integer.toString(line_id), Integer.toString(direction), Integer.toString(stop_id)}, null, null, null);
		
		if ((mCursor != null) && (mCursor.getCount() == 1)) {
			mCursor.moveToFirst();
			return mCursor.getInt(0);
		}
		Log.e(aMHDApp.TAG, "getStopOrder returns more rows.");
		return 0;
	}
	
	/**
	 * Tato metoda zisti z databazy, aka je posledna verzia zastavok
	 * @return verzia zastavok
	 */
	public int getStopRevision() {
		this.open();
		Cursor mCursor = db.query(STOP_TABLE, new String[] {"max(stop_revision) as revision"}, null, null, null, null, null);
		
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
			mCursor.moveToFirst();
			if (!mCursor.isNull(0)) {
//				Toast.makeText(mContext, Integer.toString(mCursor.getInt(0)), Toast.LENGTH_SHORT).show();
				return mCursor.getInt(0);
			}
		}
		return 0;
	}
	
	/**
	 * Tato metoda zisti z databazy, aka je posledna verzia liniek
	 * @return verzia liniek
	 */
	public int getLineRevision() {
		this.open();
		Cursor mCursor = db.query(LINE_TABLE, new String[] {"max(line_revision) as revision"}, null, null, null, null, null);
		
		if ((mCursor != null) && (mCursor.getCount() > 0)) {
			mCursor.moveToFirst();
			if (!mCursor.isNull(0)) {
//				Toast.makeText(mContext, Integer.toString(mCursor.getInt(0)), Toast.LENGTH_SHORT).show();
				return mCursor.getInt(0);
			}
		}
		return 0;
	}
	
	/**
	 * Trieda UpdateTask zabezpecuje spustenie stahovania udajov na pozadi.
	 * @author revontuli
	 *
	 */
	public class UpdateTask extends AsyncTask<Integer, Integer, Integer> {

		@Override
		protected Integer doInBackground(Integer... arg0) {
			int count = 0;
			
			Log.i(aMHDApp.TAG, "Download start");
			
			StopUpdater stopUpdater = new StopUpdater();
			ArrayList<Stop> zastavky = new ArrayList<Stop>();
			zastavky = stopUpdater.update(getStopRevision());
			Log.i(aMHDApp.TAG, "Download end, stop records: "+Integer.toString((zastavky == null)?0:zastavky.size()));
			if ((zastavky != null) && (zastavky.size() > 0)) {
				deleteStopsFromDB(zastavky);
				insertStopsIntoDB(zastavky);
				count += zastavky.size();
			}
			
			LineUpdater lineUpdater = new LineUpdater();
			ArrayList<Line> linky = new ArrayList<Line>();
			linky = lineUpdater.update(getLineRevision());
			Log.i(aMHDApp.TAG, "Download end, line records: "+Integer.toString((linky == null)?0:linky.size()));
			if ((linky != null) && (linky.size() > 0)) {
				deleteLinesFromDB(linky);
				insertLinesIntoDB(linky);
				count += linky.size();
			}
			
			DepartureUpdater departureUpdater = new DepartureUpdater();
			ArrayList<Departure> odchody = new ArrayList<Departure>();
			odchody = departureUpdater.update(0/*getLineRevision()*/, getAllFavLines()); //TODO
			Log.i(aMHDApp.TAG, "Download end, departure records: "+Integer.toString((odchody == null)?0:odchody.size()));
			if ((odchody != null) && (odchody.size() > 0)) {
				deleteDeparturesFromDB(odchody);
				insertDeparturesIntoDB(odchody);
				count += odchody.size();
			}
			
			return count;
		}
		
		protected void onPostExecute(Integer result) {
			Toast.makeText(mContext, R.string.downloadfinished, Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * Tato metoda nastavi v zdielanych nastaveniach offline/online mod
	 * @param b true pre offline, false pre online
	 */
	public void setOffline(boolean b) {
		SharedPreferences.Editor settings = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
		settings.putBoolean("settings_offlinemode", b);
		settings.commit();
	}

	/**
	 * Tato metoda zisti zo zdielanych nastaveni, ci je zapnuty offline mod.
	 * @return true pre offline, false pre online
	 */
	public boolean getOffline() {
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
		return settings.getBoolean("settings_offlinemode", false);
	}
}
